package org.mysterylab.utopiaframework.core.orm.hibernate3;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.mysterylab.utopiaframework.core.orm.Page;
import org.mysterylab.utopiaframework.core.orm.PropertyFilter;
import org.mysterylab.utopiaframework.core.orm.PropertyFilter.MatchType;
import org.mysterylab.utopiaframework.util.reflect.ReflectionUtil;
import org.springframework.util.Assert;

/**
 * 在 {@link BaseHibernateDao} 的基础上加入了如下特性:
 * <ul>
 * 	<li>1) 分页查询.</li>
 * 	<li>2) 按属性过滤条件列表查询.</li>
 * </ul>
 *
 * @param <T>
 *            DAO 操作的对象类型
 * @param <PK>
 *            主键类型
 *            
 * @author zhouych
 * @see PropertyFilter
 */
public class HibernateDao<T, PK extends Serializable> extends BaseHibernateDao<T, PK> {

	/**
	 * 通过子类的泛型定义获得对象的类型.<br>
	 * 比如: 
	 * <pre>
	 * {@code
	 *  public class UserDao extends HibernateDao<User, Long>
	 * }
	 * </pre>
	 */
	public HibernateDao() {
		super();
	}
	
	/**
	 * 跳过 DAO 层, 直接在 Service 层使用 BaseHibernateDao 的构造函数,
	 * 在构造函数中定义对象类型.
	 * <pre>
	 * {@code
	 *   HibernateDao<User, Long> userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
	 * }
	 * </pre>
	 * @param sessionFactory
	 * @param entityClass
	 */
	public HibernateDao(final SessionFactory sessionFactory,
			final Class<T> entityClass) {
		super(sessionFactory, entityClass);
	}
	
	/**
	 * 分页获取全部对象.
	 * 
	 * @param page
	 * @return
	 */
	public Page<T> getAll(final Page<T> page) {
		return findPage(page);
	}

	/**
	 * 按 HQL 分页查询.
	 * 
	 * @param page
	 *            分页参数. 注意不支持其中的 orderBy 参数
	 * @param hql
	 *            hql 语句
	 * @param values
	 *            数量可变的查询参数,按顺序绑定
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final String hql,
			final Object... values) {
		
		Assert.notNull(page, "page can not be null");
		Query query = createQuery(hql, values);
		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}
		setPageParameterToQuery(query, page);
		
		List result = query.list();
		page.setResult(result);
		return page;
	}
	
	/**
	 * 按 HQL 分页查询.
	 * 
	 * @param page
	 *            分页参数. 注意不支持其中的 orderBy 参数
	 * @param hql
	 *            hql 语句
	 * @param values
	 *            命名参数, 按名称绑定
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final String hql,
			final Map<String, ?> values) {
		
		Assert.notNull(page, "page can not be null");
		Query query = createQuery(hql, values);
		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}
		setPageParameterToQuery(query, page);

		List result = query.list();
		page.setResult(result);
		return page;
	}
	
	/**
	 * 按 Criteria 分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param criterions
	 *            数量可变的 Criterion
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page, "page can not be null");

		Criteria criteria = createCriteria(criterions);
		if (page.isAutoCount()) {
			long totalCount = countCriteriaResult(criteria);
			page.setTotalCount(totalCount);
		}
		setPageParameterToCriteria(criteria, page);

		List result = criteria.list();
		page.setResult(result);
		return page;
	}
	
	/**
	 * 设置分页参数到 Query 对象, 辅助函数.
	 * 
	 * @param query
	 * @param page
	 * @return
	 */
	protected Query setPageParameterToQuery(final Query query, final Page<T> page) {

		Assert.isTrue(page.getPageSize() > 0, "Page#pageSize must larger than 0");

		// 注意 Hibernate 的 firstResult 的序号从 0 开始
		query.setFirstResult(page.getFirst() - 1);
		query.setMaxResults(page.getPageSize());
		return query;
	}
	
	/**
	 * 设置分页参数到 Criteria 对象, 辅助函数.
	 * 
	 * @param criteria
	 * @param page
	 * @return
	 */
	protected Criteria setPageParameterToCriteria(final Criteria criteria,
			final Page<T> page) {

		Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		// 注意 Hibernate 的 firstResult 的序号从 0 开始
		criteria.setFirstResult(page.getFirst() - 1);
		criteria.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');

			Assert.isTrue(orderByArray.length == orderArray.length,
					"分页多重排序参数中, 排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					criteria.addOrder(Order.asc(orderByArray[i]));
				} else {
					criteria.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return criteria;
	}
	
	/**
	 * 执行 count 查询获得本次 Hql 查询所能获得的对象总数.<br>
	 * 注意本函数只能自动处理简单的 hql 语句, 复杂的 hql 查询请另行编写 count 语句查询.
	 * 
	 * @param hql
	 * @param values
	 * @return
	 */
	protected long countHqlResult(final String hql, final Object... values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}
	
	/**
	 * 执行 count 查询获得本次 Hql 查询所能获得的对象总数.<br>
	 * 注意本函数只能自动处理简单的 hql 语句, 复杂的 hql 查询请另行编写 count 语句查询.
	 * 
	 * @param hql
	 * @param values
	 * @return
	 */
	protected long countHqlResult(final String hql, final Map<String, ?> values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}
	
	/**
	 * 为 count 查询获得 Hql 查询获得的对象总数做预处理.
	 * 
	 * @param orgHql
	 * @return
	 */
	private String prepareCountHql(String orgHql) {
		String fromHql = orgHql;
		/*
		 * select 子句与 order by 子句会影响 count 查询, 进行简单的排除. 比如:
		 * select name from order as o order by o.number asc -> from order as o
		 */
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;
		return countHql;
	}
	
	/**
	 * 执行 count 查询获得本次 Criteria 查询所能获得的对象总数.
	 * 
	 * @param criteria
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected long countCriteriaResult(final Criteria criteria) {
		CriteriaImpl impl = (CriteriaImpl) criteria;

		// 先把 Projection、ResultTransformer、OrderBy 取出来, 清空三者后再执行 Count 操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtil.getFieldValue(impl, "orderEntries");
			ReflectionUtil.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("exception could not be happened", e.getMessage());
		}

		// 执行 Count 查询
		Long totalCountObject = (Long) criteria.setProjection(Projections.rowCount())
				.setMaxResults(1).uniqueResult();
		long totalCount = (totalCountObject != null) ? totalCountObject : 0;

		// 将之前的 Projection, ResultTransformer 和 OrderBy 条件重新设回去
		criteria.setProjection(projection);

		if (projection == null) {
			criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			criteria.setResultTransformer(transformer);
		}
		try {
			ReflectionUtil.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("exception could not be happened", e.getMessage());
		}

		return totalCount;
	}
	
	/**
	 * 按属性查找对象列表, 支持多种匹配方式.
	 * 
	 * @param matchType
	 *            匹配方式, 目前支持的取值见 {@link PropertyFilter} 的 MatcheType enum
	 */
	public List<T> findBy(final String propertyName, final Object value,
			final MatchType matchType) {
		Criterion criterion = buildCriterion(propertyName, value, matchType);
		return find(criterion);
	}
	
	/**
	 * 按属性过滤条件列表查找对象列表.
	 * 
	 * @param filters
	 * @return
	 */
	public List<T> find(List<PropertyFilter> filters) {
		Criterion[] criterions = buildCriterionByPropertyFilter(filters);
		return find(criterions);
	}
	
	/**
	 * 按属性过滤条件列表分页查找对象.
	 * 
	 * @param page
	 * @param filters
	 * @return
	 */
	public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildCriterionByPropertyFilter(filters);
		return findPage(page, criterions);
	}
	
	/**
	 * 按属性条件参数创建 Criterion, 辅助函数.
	 * 
	 * @param propertyName
	 * @param propertyValue
	 * @param matchType
	 * @return
	 */
	protected Criterion buildCriterion(final String propertyName,
			final Object propertyValue, final MatchType matchType) {
		Assert.hasText(propertyName, "propertyName can not be null");
		Criterion criterion = null;
		// 根据 MatchType 构造 criterion
		switch (matchType) {
		
			case EQ:
				criterion = Restrictions.eq(propertyName, propertyValue);
				break;
				
			case LIKE:
				criterion = Restrictions.like(propertyName, (String) propertyValue,
						MatchMode.ANYWHERE);
				break;

			case LE:
				criterion = Restrictions.le(propertyName, propertyValue);
				break;
				
			case LT:
				criterion = Restrictions.lt(propertyName, propertyValue);
				break;
				
			case GE:
				criterion = Restrictions.ge(propertyName, propertyValue);
				break;
				
			case GT:
				criterion = Restrictions.gt(propertyName, propertyValue);
		}
		return criterion;
	}
	
	/**
	 * 按属性条件列表创建 Criterion 数组, 辅助函数.
	 * 
	 * @param filters
	 * @return
	 */
	protected Criterion[] buildCriterionByPropertyFilter(
			final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			if (!filter.hasMultiProperties()) {
				// 只有一个属性需要比较的情况
				Criterion criterion = buildCriterion(filter.getPropertyName(),
						filter.getMatchValue(), filter.getMatchType());
				criterionList.add(criterion);
			} else {
				// 包含多个属性需要比较的情况,进行or处理
				Disjunction disjunction = Restrictions.disjunction();
				for (String param : filter.getPropertyNames()) {
					Criterion criterion = buildCriterion(param, filter
							.getMatchValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}
}
